#!/usr/bin/env python

import ConfigParser
import os
import sys

try:
    import Pyro.core
except ImportError:
    print "Missing Pyro module, you will need to install Pyro"
    print "before running astmonpy, check http://pyro.sourceforge.net"
    sys.exit(1)

from astmonhoststats import *

if __name__ == "__main__":
    astmonpysrvconf = "astmonpysrv.conf"

    config = ConfigParser.ConfigParser()
    config.read(astmonpysrvconf)
    try:
        daemon = config.get("server", "daemon")
        asteriskbin = config.get("server", "asteriskbin")
    except ConfigParser.NoOptionError, reason:
        print "Missing config option:", reason
        sys.exit(1)
    except ConfigParser.NoSectionError:
        print "Config file error, setting up default values..."
        daemon = 1
        asteriskbin = "/usr/sbin/asterisk"

    if daemon == "1":
        # fork
        pid = os.fork()
    else:
        pid = 0
    if pid == 0:
        Pyro.core.initServer()
        daemon = Pyro.core.Daemon()
        uri = daemon.connect(AstmonHostStats(asteriskbin), "AstmonHostStats")
        try:
            daemon.requestLoop()
        except KeyboardInterrupt:
            sys.exit(0)
    else:
        sys.exit(0)
